package com.weasel.weixin.mp.servlet;

import com.weasel.helper.JsonHelper;
import com.weasel.weixin.commons.accounts.Oauth2AccessTokenResponse;
import com.weasel.weixin.commons.user.UserInfoRequest;
import com.weasel.weixin.commons.user.UserInfoResponse;
import com.weasel.weixin.mp.builder.MpConfigBuilder;
import com.weasel.weixin.mp.config.MpConfig;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Dylan on 2015/9/28.
 */
public class Oauth2UserInfoServlet extends HttpServlet {


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        MpConfig config = MpConfigBuilder.fromXML("classpath:weixin-config.xml");

        String code = request.getParameter("code");
        String state = request.getParameter("state");

        Oauth2AccessTokenResponse accessTokenResponse = Oauth2AccessTokenServlet.cache.getIfPresent("oauth2_access_token");

        if(null == accessTokenResponse){
            response.getWriter().write("用户还没授权，请先授权");
            return;
        }

        UserInfoResponse userInfoResponse = UserInfoRequest.getOauth2UserInfo(accessTokenResponse.getAccessToken(), accessTokenResponse.getOpenId());

        response.getWriter().write(JsonHelper.toJsonString(userInfoResponse));
    }
}
